package com.hh.game.service.gateway.pool;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import com.hh.game.common.base.cache.redis.RedisResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class WorkResultDataPoolLocal implements WorkResultDataPool {
    private Map<Integer, Cache<Long, Object>> dataPool = new ConcurrentHashMap<>(256);

    @Override
    public Object get(int userId, long requestId) {
        Object result = null;
        Cache<Long, Object> cache = dataPool.get(userId);
        if (cache != null) {
            result = cache.get(requestId);
        }
        return result;
    }

    @Override
    public void set(int userId, long requestId, Object result) {
        Cache<Long, Object> cache = dataPool.get(userId);
        if (cache == null) {
            cache = CacheUtil.newFIFOCache(20, 100L);
            cache = dataPool.putIfAbsent(userId, cache);
        }
        cache.put(requestId , result);
    }

    @Override
    public int size() {
        return (int)dataPool.values().stream()
                .collect(Collectors.summarizingInt(cache -> cache.size())).getSum();
    }

    @Override
    public void clear() {
        dataPool.clear();
    }
}
